from aip import AipOcr
import os

file_list = []

def get_file_list(dir_path):   #递归遍历目录，将.png结尾的文件路径加入文件列表
    for i in os.listdir(dir_path):
        path = os.path.join(dir_path,i)
        if os.path.isdir(path):
            get_file_list(path)
        if path.endswith(".png"):
            file_list.append(path)

def basicAccOCR(client,file_path):
    with open(file_path,'rb') as f:
        image=f.read()

    return client.basicAccurate(image)

def webImageOCR(client):
    url = "http://img0.imgtn.bdimg.com/it/u=2859753920,13388660&fm=214&gp=0.jpg"
    return client.webImageUrl(url);

if __name__ == '__main__':
    """ 你的 APPID AK SK """
    APP_ID = 'XXXXXX'
    API_KEY = 'XXXXXXXXXXXXXXXXXXX'
    SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

    client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

   # text =  webImageOCR(client)   #basicAccOCR(client)

    get_file_list('e:/program/baiduOCR/')
    for i in file_list:
        print('========%s========' %i)
        text =  basicAccOCR(client,i)
        result = text["words_result"]
        for j in result:
            print (j["words"])
        print(' ')

'''
https://ai.baidu.com/tech/ocr/general

通用文字识别

用户向服务请求识别某张图中的所有文字

""" 读取图片 """
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()

image = get_file_content('example.jpg')

""" 调用通用文字识别, 图片参数为本地图片 """
client.basicGeneral(image);

""" 如果有可选参数 """
options = {}
options["language_type"] = "CHN_ENG"
options["detect_direction"] = "true"
options["detect_language"] = "true"
options["probability"] = "true"

""" 带参数调用通用文字识别, 图片参数为本地图片 """
client.basicGeneral(image, options)

url = "https//www.x.com/sample.jpg"

""" 调用通用文字识别, 图片参数为远程url图片 """
client.basicGeneralUrl(url);

""" 如果有可选参数 """
options = {}
options["language_type"] = "CHN_ENG"
options["detect_direction"] = "true"
options["detect_language"] = "true"
options["probability"] = "true"

""" 带参数调用通用文字识别, 图片参数为远程url图片 """
client.basicGeneralUrl(url, options)
'''

'''
通用文字识别（高精度版）

用户向服务请求识别某张图中的所有文字，相对于通用文字识别该产品精度更高，但是识别耗时会稍长。

""" 读取图片 """
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()

image = get_file_content('example.jpg')

""" 调用通用文字识别（高精度版） """
client.basicAccurate(image);

""" 如果有可选参数 """
options = {}
options["detect_direction"] = "true"
options["probability"] = "true"

""" 带参数调用通用文字识别（高精度版） """
client.basicAccurate(image, options)
'''